#!/usr/bin/env python3
import socket
import ipaddress
import threading
import time

# 定义要扫描的IP地址范围
network = "192.168.88.0/24"
# SSH默认端口
port = 22
# 超时时间（秒）
timeout = 0.5
# 线程锁，用于安全打印
print_lock = threading.Lock()

def scan_ip(ip):
    try:
        # 创建socket对象
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            # 设置超时时间
            s.settimeout(timeout)
            # 尝试连接
            result = s.connect_ex((str(ip), port))
            if result == 0:
                with print_lock:
                    print(f"找到SSH服务: {ip}")
    except Exception as e:
        with print_lock:
            print(f"扫描 {ip} 时出错: {e}")

def main():
    print(f"开始扫描 {network} 网段的SSH服务...")
    start_time = time.time()
    
    # 创建线程列表
    threads = []
    # 遍历网段内的所有IP地址
    for ip in ipaddress.IPv4Network(network, strict=False):
        # 跳过网络地址和广播地址
        if ip == ipaddress.IPv4Address("192.168.88.1") or ip == ipaddress.IPv4Address("192.168.88.255"):
            continue
        # 创建并启动线程
        t = threading.Thread(target=scan_ip, args=(ip,))
        threads.append(t)
        t.start()
    
    # 等待所有线程完成
    for t in threads:
        t.join()
    
    end_time = time.time()
    print(f"扫描完成，耗时: {end_time - start_time:.2f} 秒")

if __name__ == "__main__":
    main()    